package com.lanou.moving.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lanou.moving.R;
import com.lanou.moving.activity.EveryoneMoreActivity;
import com.lanou.moving.activity.MVPlayActivity;
import com.lanou.moving.activity.PlayMusicActivity;
import com.lanou.moving.activity.RankingListActivity;
import com.lanou.moving.activity.SingerActivity;
import com.lanou.moving.activity.SongListActivity;
import com.lanou.moving.activity.SongListDetailActivity;
import com.lanou.moving.activity.WebViewActivity;
import com.lanou.moving.adapter.FindGridviewAdapter;
import com.lanou.moving.adapter.FindListViewAdapter;
import com.lanou.moving.adapter.FindViewPagerAdapter;
import com.lanou.moving.base.BaseFragment;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.FindRoot;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.ui.PullToRefreshView;
import com.lanou.moving.view.MyGridView;
import com.lanou.moving.view.MyListView;
import com.lanou.moving.volley.GsonRequest;
import com.lanou.moving.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by dllo on 15/10/20.
 */
public class FindFragment extends BaseFragment implements ViewPager.OnPageChangeListener,
        PullToRefreshView.OnRefreshListener, View.OnClickListener {
    private Context context;
    private ImageView[] tips;
    private ViewPager mViewPager;
    private FindViewPagerAdapter findViewPagerAdapter;
    private LinearLayout linearLayout_head_viewpager;
    private ArrayList<FindRoot.DatasEntity.DataEntity> dataEntityArrayList;
    private ArrayList<FindRoot.DatasEntity> datasEntityArrayList;
    private Runnable runnable;
    private GsonRequest<FindRoot> findRootGsonRequest;
    private VolleySingleton volleySingleton;
    private View view;
    private String pic_url;
    private String value;

    private ImageView find_rangk_img, find_songlist_img, find_radio_img, find_singer_img;
    private TextView everyone_listening_name, songs_list_number, everyone_listening_more, find_weekend_tv,
            everyone_listening_song_name, everyone_listening_singer, hot_more, new_more,
            theme_more,  mv_more;

    private ImageView everyone_listening_image;
    private int[] id = {R.id.include_one, R.id.include_two, R.id.include_three};

    private MyGridView find_hot_songs_gridview, find_weekend_gridview,
            find_latest_music_grideview, find_latest_mv_grideview, find_activity_area_grideview;
    private FindGridviewAdapter findGridviewAdapter;

    private MyListView find_music_ten_listview, find_music_theme_listview;
    private FindListViewAdapter findListViewAdapter;

    private Intent intent = new Intent();

    private LinearLayout find_ranklist_linear, find_songlist_linear, find_radio_linear, finde_singer_linear;

    private List<MusicInfo> musicInfoList;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_find, null);
        volleySingleton = VolleySingleton.getInstance(context);
        mViewPager = (ViewPager) view.findViewById(R.id.find_head_viewpager);
        find_hot_songs_gridview = (MyGridView) view.findViewById(R.id.find_hot_songs_gridview);
        find_hot_songs_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                value = datasEntityArrayList.get(3).getData().get(position).getAction().getValue();
                intent.setClass(getActivity(), SongListDetailActivity.class);
                intent.putExtra("id", Integer.valueOf(value));
                intent.putExtra("position", 3);
                getActivity().startActivity(intent);
            }
        });
        find_weekend_gridview = (MyGridView) view.findViewById(R.id.find_weekend_gridview);//周末来了
        find_weekend_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                value = datasEntityArrayList.get(4).getData().get(position).getAction().getValue();
                intent.setClass(getActivity(), SongListDetailActivity.class);
                intent.putExtra("id", Integer.valueOf(value));
                intent.putExtra("position", 4);
                getActivity().startActivity(intent);
            }
        });
        find_latest_music_grideview = (MyGridView) view.findViewById(R.id.find_latest_music_grideview);//最新音乐
        find_latest_music_grideview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        NewSongSelection newSongSelection = new NewSongSelection();
                        getFragmentManager().beginTransaction().replace(android.R.id.content, newSongSelection).addToBackStack(null).commit();
                        break;
                    case 1:
                        value = datasEntityArrayList.get(7).getData().get(1).getAction().getValue();
                        AlbumDetailFragment albumDetailFragment = new AlbumDetailFragment();
                        Bundle bundle = new Bundle();
                        bundle.putLong("albumId", Long.valueOf(value));
                        albumDetailFragment.setArguments(bundle);
                        getFragmentManager().beginTransaction().add(android.R.id.content, albumDetailFragment).addToBackStack(null).commit();
                        break;
                    case 2:
                        value = datasEntityArrayList.get(7).getData().get(2).getAction().getValue();
                        AlbumDetailFragment detalFragment = new AlbumDetailFragment();
                        Bundle bundle1 = new Bundle();
                        bundle1.putLong("albumId", Long.valueOf(value));
                        detalFragment.setArguments(bundle1);
                        getFragmentManager().beginTransaction().add(android.R.id.content, detalFragment).addToBackStack(null).commit();
                        break;
                }
            }
        });
        find_latest_mv_grideview = (MyGridView) view.findViewById(R.id.find_latest_mv_grideview);//最新mv
        find_music_ten_listview = (MyListView) view.findViewById(R.id.find_music_ten_listview);//每日十首
        find_music_theme_listview = (MyListView) view.findViewById(R.id.find_music_theme_listview);//音乐专题
        find_activity_area_grideview = (MyGridView) view.findViewById(R.id.find_activity_area_grideview);//独家专区
        linearLayout_head_viewpager = (LinearLayout) view.findViewById(R.id.linearLayout_head_viewpager);
        initView();
        getFindRoot();
        return view;
    }


    public void initView() {
        find_rangk_img = (ImageView) view.findViewById(R.id.find_rangk_img);//排行榜
        find_songlist_img = (ImageView) view.findViewById(R.id.find_songlist_img);//歌单
        find_radio_img = (ImageView) view.findViewById(R.id.find_radio_img);//电台
        find_singer_img = (ImageView) view.findViewById(R.id.find_singer_img);//歌手
        everyone_listening_name = (TextView) view.findViewById(R.id.everyone_listening_name);//大家在听
        everyone_listening_more = (TextView) view.findViewById(R.id.everyone_listening_more);//更多
        everyone_listening_more.setOnClickListener(this);

        //排行榜按钮
        find_ranklist_linear = (LinearLayout) view.findViewById(R.id.find_ranklist_linear);
        find_ranklist_linear.setOnClickListener(this);
        //歌单按钮
        find_songlist_linear = (LinearLayout) view.findViewById(R.id.find_songlist_linear);
        find_songlist_linear.setOnClickListener(this);
        //电台按钮
        find_radio_linear = (LinearLayout) view.findViewById(R.id.find_radio_linear);
        find_radio_linear.setOnClickListener(this);
        //歌手按钮
        finde_singer_linear = (LinearLayout) view.findViewById(R.id.finde_singer_linear);
        finde_singer_linear.setOnClickListener(this);
        //热门歌单
        hot_more = (TextView) view.findViewById(R.id.hot_more);
        hot_more.setOnClickListener(this);
        //最新音乐
        new_more = (TextView) view.findViewById(R.id.new_more);
        new_more.setOnClickListener(this);
        //音乐专题
        theme_more = (TextView) view.findViewById(R.id.theme_more);
        theme_more.setOnClickListener(this);


        //最新MV
        mv_more = (TextView) view.findViewById(R.id.mv_more);
        mv_more.setOnClickListener(this);

        //周末来了
        find_weekend_tv = (TextView) view.findViewById(R.id.find_weekend_tv);

    }

    // 大家在听
    private void setEveryone() {
        for (int i = 0; i < 3; i++) {
            final int index =i;
            View everyoneView = view.findViewById(id[i]);
            songs_list_number = (TextView) everyoneView.findViewById(R.id.songs_list_number);//序号
            everyone_listening_song_name = (TextView) everyoneView.findViewById(R.id.everyone_listening_song_name);//歌名
            everyone_listening_singer = (TextView) everyoneView.findViewById(R.id.everyone_listening_singer);//歌手
            everyone_listening_image = (ImageView) everyoneView.findViewById(R.id.everyone_listening_image);//图片
            pic_url = datasEntityArrayList.get(2).getData().get(0).getSongs().get(i).getPicUrl();
            songs_list_number.setText(String.valueOf(i + 1));
            everyone_listening_song_name.setText(datasEntityArrayList.get(2).getData().get(0).getSongs().get(i).getName());
            everyone_listening_singer.setText(datasEntityArrayList.get(2).getData().get(0).getSongs().get(i).getSingerName());
            Picasso.with(context).load(pic_url).into(everyone_listening_image);
            everyoneView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new MyEventBus.PlayMusic(1));
                    musicInfoList = new ArrayList<>();
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getName());
                    musicInfo.setAlbum(datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getAlbumName());
                    musicInfo.setAlbumId(datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getAlbumId());
                    musicInfo.setUrl(datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getAuditionList().get(1).getUrl());
                    musicInfo.setDuration(datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getAuditionList().get(1).getDuration());
                    musicInfo.setSingerName(datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);

                    intent.setClass(getActivity(), PlayMusicActivity.class);
                    EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getName()));
                    intent.putExtra("songName", datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getName());
                    intent.putExtra("duration", datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getAuditionList().get(1).getDuration());
                    intent.putExtra("resource", "网络");
                    intent.putExtra("albumId", datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getAlbumId());
                    intent.putExtra("singerName", datasEntityArrayList.get(2).getData().get(0).getSongs().get(index).getSingerName());
                    startActivity(intent);
                }
            });
        }
    }

    public void getFindRoot() {
        findRootGsonRequest = new GsonRequest<>(URL.URL_FOUND, FindRoot.class, new Response.Listener<FindRoot>() {
            @Override
            public void onResponse(FindRoot response) {
                datasEntityArrayList = response.getData();
                dataEntityArrayList = datasEntityArrayList.get(0).getData();
                findViewPagerAdapter = new FindViewPagerAdapter(context, dataEntityArrayList);
                mViewPager.setAdapter(findViewPagerAdapter);
                initdots();
                ImageRun();
                mViewPager.setCurrentItem(0);
                mViewPager.addOnPageChangeListener(FindFragment.this);

                //设置界面
                setDatas();

                //大家在听
                setEveryone();

                //热门歌单
                findGridviewAdapter = new FindGridviewAdapter(context, datasEntityArrayList.get(3).getData());
                find_hot_songs_gridview.setAdapter(findGridviewAdapter);

                //周末来了
                findGridviewAdapter = new FindGridviewAdapter(context, datasEntityArrayList.get(4).getData());
                find_weekend_gridview.setAdapter(findGridviewAdapter);
                find_weekend_tv.setText(dataEntityArrayList.get(4).getName());

                //最新音乐
                findGridviewAdapter = new FindGridviewAdapter(context, datasEntityArrayList.get(7).getData());
                find_latest_music_grideview.setAdapter(findGridviewAdapter);

                //最新MV
                findGridviewAdapter = new FindGridviewAdapter(context, datasEntityArrayList.get(8).getData());
                find_latest_mv_grideview.setAdapter(findGridviewAdapter);
                find_latest_mv_grideview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        intent.setClass(getActivity(), MVPlayActivity.class);
                        intent.putExtra("videoId", Integer.valueOf(datasEntityArrayList.get(8).getData().get(position)
                                .getAction().getValue()));
                        Log.i("videoid", "+++++ " + datasEntityArrayList.get(8).getData().get(position)
                                .getAction().getValue());
                        startActivity(intent);
                    }
                });

                //每日十首
                findListViewAdapter = new FindListViewAdapter(context, datasEntityArrayList.get(10).getData());
                find_music_ten_listview.setAdapter(findListViewAdapter);
                find_music_ten_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        intent.setClass(getActivity(), SongListDetailActivity.class);
                        intent.putExtra("id", Integer.valueOf(datasEntityArrayList.get(10).getData().get(position).getAction().getValue()));
                        startActivity(intent);
                    }
                });


                //音乐专题
                findListViewAdapter = new FindListViewAdapter(context, datasEntityArrayList.get(11).getData());
                find_music_theme_listview.setAdapter(findListViewAdapter);

                find_music_theme_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        intent.setClass(context, WebViewActivity.class);
                        intent.putExtra("link", datasEntityArrayList.get(11).getData().get(position).getAction().getValue());
                        startActivity(intent);
                    }
                });


                //活动专区
                findGridviewAdapter = new FindGridviewAdapter(context, datasEntityArrayList.get(12).getData());
                find_activity_area_grideview.setAdapter(findGridviewAdapter);
                find_activity_area_grideview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        intent.setClass(context, WebViewActivity.class);
                        intent.putExtra("link", datasEntityArrayList.get(12).getData().get(position).getAction().getValue());
                        startActivity(intent);
                    }
                });


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(findRootGsonRequest);
    }

    public void setDatas() {
        //快捷分类
        Picasso.with(context).load(datasEntityArrayList.get(1).getData().get(0).getPicUrl()).into(find_rangk_img);
        Picasso.with(context).load(datasEntityArrayList.get(1).getData().get(1).getPicUrl()).into(find_songlist_img);
        Picasso.with(context).load(datasEntityArrayList.get(1).getData().get(2).getPicUrl()).into(find_radio_img);
        Picasso.with(context).load(datasEntityArrayList.get(1).getData().get(3).getPicUrl()).into(find_singer_img);
        //大家在听
        everyone_listening_name.setText(datasEntityArrayList.get(2).getData().get(0).getDesc());
    }

    public void initdots() {
        tips = new ImageView[dataEntityArrayList.size()];
        for (int i = 0; i < tips.length; i++) {
            ImageView imageView = new ImageView(context);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
            tips[i] = imageView;
            if (i == 0) {
                tips[i].setBackgroundResource(R.mipmap.img_page_indicator_selected);
            } else {
                tips[i].setBackgroundResource(R.mipmap.img_page_indicator);
            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 5;
            layoutParams.rightMargin = 5;
            linearLayout_head_viewpager.addView(imageView, layoutParams);
        }
    }

    /**
     * 轮播图时间的设置
     */
    private Handler handler = new Handler();

    protected void ImageRun() {
        runnable =
                new Runnable() {
            @Override
            public void run() {
                int index = mViewPager.getCurrentItem();
                if (index == dataEntityArrayList.size() - 1) {
                    index = -1;
                }
                mViewPager.setCurrentItem(++index);
                handler.postDelayed(runnable, 3000);
            }
        };
        handler.postDelayed(runnable, 3000);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < tips.length; i++) {
            if (i == position) {
                tips[i].setBackgroundResource(R.mipmap.img_page_indicator_selected);
            } else {
                tips[i].setBackgroundResource(R.mipmap.img_page_indicator);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onClick(View v) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        switch (v.getId()) {
            case R.id.find_ranklist_linear:
                intent.setClass(getActivity(), RankingListActivity.class);
                startActivity(intent);
                break;
            case R.id.finde_singer_linear:
                intent.setClass(getActivity(), SingerActivity.class);
                startActivity(intent);
                break;
            case R.id.find_radio_linear:
                ft.replace(android.R.id.content, new RadioStationFragment())
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .addToBackStack(null);
                break;
            case R.id.find_songlist_linear:
                intent.setClass(getActivity(), SongListActivity.class);
                startActivity(intent);
                break;
            case R.id.everyone_listening_more:
                intent.setClass(getActivity(), EveryoneMoreActivity.class);
                intent.putExtra("pic_url", pic_url);
                startActivity(intent);
                break;

            case R.id.hot_more://热门歌单
                intent.setClass(getActivity(), SongListActivity.class);
                startActivity(intent);
                break;
            case R.id.new_more://最新音乐
                ft.replace(android.R.id.content, new LatestMusicFragment()).addToBackStack(null);
                break;

            case R.id.theme_more://音乐专题
                ft.add(android.R.id.content, new MusicThemeFragment()).addToBackStack(null);
                break;



            case R.id.mv_more://最新MV
                MVAreaFragment mvAreaFragment = new MVAreaFragment();
                ft.replace(android.R.id.content, mvAreaFragment).addToBackStack(null);
                break;

        }
        ft.commit();
    }
}
